<template>
  <el-card
    class="article-detail"
    v-loading="loading"
    element-loading-text="加载中..."
  >
    <!-- 外层条件：加载完成后才显示内容 -->
    <div v-if="!loading">
      <!-- 错误提示 -->
      <div v-if="error" class="error-tip">
        加载文章失败：{{ error.message }}
      </div>

      <!-- 文章内容 -->
      <div v-else class="article-content">
        <div class="article-header">
          <el-button
            type="text"
            icon="ElIconArrowLeft"
            @click="goBack"
            class="back-btn"
          >
            返回
          </el-button>
          <h1 class="article-title">{{ article.title }}</h1>
        </div>

        <div class="article-meta">
          <span>作者：{{ author }}</span>
          <span>发布时间：{{ formatCreatedAt }}</span>
        </div>
        <div class="article-body" v-html="renderedMarkdown"></div>
      </div>
    </div>
  </el-card>
</template>

<script>
import { getArticleDetail, getUserInfo } from "@/api";
import dayjs from "dayjs";
import { marked } from "marked";
// marked.setOptions({
//   sanitize: true, // 启用 HTML 标签清理
// });

export default {
  data() {
    return {
      article: {},
      author: "",
      loading: true,
      error: null,
    };
  },
  computed: {
    formatCreatedAt() {
      return this.article.created_at
        ? dayjs(this.article.created_at).format("YYYY年MM月DD日")
        : "未知时间";
    },
    renderedMarkdown() {
      if (this.article.content) {
        return marked(this.article.content);
      }
      return "";
    },
  },
  async created() {
    try {
      const articleId = this.$route.params.id;
      const res = await getArticleDetail(articleId);
      const articleData = res.data?.data;
      if (!articleData || !articleData.user_id) {
        throw new Error("文章数据或用户ID缺失");
      }

      const userInfo = await getUserInfo(articleData.user_id);
      this.author = userInfo.data?.user?.username || "未知作者";
      this.article = articleData;
    } catch (err) {
      this.error = err;
    } finally {
      this.loading = false;
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
  },
};
</script>

<style scoped>
.article-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.back-btn {
  margin-right: 15px;
  padding: 0;
  font-size: 16px;
  color: #606266;
}

.back-btn:hover {
  color: #409eff;
}

.article-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 0;
  color: #303133;
}

.article-meta {
  font-size: 14px;
  color: #606266;
  margin-bottom: 25px;
}
.article-detail {
  max-width: 800px;
  margin: 30px auto;
  padding: 20px 30px;
}

.article-meta span {
  margin-right: 20px;
}

.article-body {
  font-size: 16px;
  line-height: 1.8;
  color: #303133;
}

.error-tip {
  color: #f56c6c;
  font-size: 16px;
  text-align: center;
  padding: 20px;
}
</style>
